import { Frame } from './Frame';
import { ViewController } from './ViewController';

/**
 * View class - Base class for all views in Mini-XAF.
 * Views display data to the user.
 */
export abstract class View {
  private _id: string;
  private _caption: string;
  private _frame: Frame | null = null;
  private _controllers: ViewController[] = [];

  /**
   * Create a new View
   * @param id View identifier
   * @param caption View caption
   */
  constructor(id: string, caption: string) {
    this._id = id;
    this._caption = caption;
  }

  /**
   * Get the view ID
   */
  public get id(): string {
    return this._id;
  }
  
  /**
   * Get the view name (alias for id for compatibility with model structure)
   */
  public get name(): string {
    return this._id;
  }

  /**
   * Get the view caption
   */
  public get caption(): string {
    return this._caption;
  }

  /**
   * Set the view caption
   */
  public set caption(value: string) {
    this._caption = value;
  }

  /**
   * Get the frame containing this view
   */
  public get frame(): Frame | null {
    return this._frame;
  }
  /**
   * Set the frame for this view
   * @param frame The frame containing this view
   */
  public setFrame(frame: Frame | null): void {
    this._frame = frame;
  }
  /**
   * Add a view controller to this view
   * @param controller The controller to add
   */
  public addController(controller: ViewController): void {
    if (!this._controllers.includes(controller)) {
      console.log(`View ${this._id}: Adding controller ${controller.id}`);
      this._controllers.push(controller);
      controller.setView(this);
      // Log controller actions for debugging
      console.log(`View ${this._id}: Controller ${controller.id} has ${controller.actions.length} actions`);
    }
  }

  /**
   * Get all controllers registered with this view
   */
  public get controllers(): ViewController[] {
    return [...this._controllers];
  }

  /**
   * Find a controller of the specified type
   * @param type The constructor of the controller type to find
   */
  public getController<T extends ViewController>(type: new (...args: any[]) => T): T | null {
    for (const controller of this._controllers) {
      if (controller instanceof type) {
        return controller as T;
      }
    }
    return null;
  }
  /**
   * Render this view - to be implemented by subclasses
   */
  public abstract render(): any;
}
